package com.apes.fa.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fa.model.*;
import com.apes.fa.respository.FaCardImportRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.FaCategory;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.FaCategoryRepository;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.rbac.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fa.service
 * @ClassName: FaAssetInvestService
 * @Author: cxm
 * @Description: 批量导入
 * @CreateTime: 2022-02-14 15:16
 * @Version: 1.0
 */
@Service("faCardImportService")
public class FaCardImportService extends DomainService {

    @Autowired
    private FaCardImportRepository faCardImportRepository;
    @Autowired
    private FaCardService faCardService;
    /**
     * 保存
     */
    public FaCardImport save(SimpleRequest request){

        FaCardImport faCardImport = request.getO(FaCardImport.class);
        faCardImport.setState("create");
        return faCardImportRepository.saveAndFlush(faCardImport);

    }

    /**
     * 删除
     */
    public String delete(SimpleRequest request){
        FaCardImport faCardImport = request.getO(FaCardImport.class);
        faCardImportRepository.delete(faCardImport);
        return "删除成功！";
    }

    /**
     * 审核并生成卡片
     */
    public FaCardImport approve(SimpleRequest request){

        FaCardImport faCardImport = request.getO(FaCardImport.class);
        faCardImport.setState("approve");
        faCardImport.setApproveDate(new Date());
        faCardImport.setApproveUid(this.getPerson(request));
        List<FaCardImportItem> faCardImportItems = faCardImport.getFaCardImpItems();
        for (FaCardImportItem faCardImportItem : faCardImportItems) {

            FaCard faCard = new FaCard();
            Product product = new Product();
            FaCategory faCategory = new FaCategory();
            PartyRole company = new PartyRole();
            Dept dept = new Dept();
            faCard.setId(faCardImportItem.getId());
            faCard.setFaId(faCardImportItem.getFaId());
            faCard.setBusinessName("期初导入");//单据类型名称
            faCard.setSourceBusinessType("init");//来源单据类型
            faCard.setSourceBusinessKey(faCardImport.getId());//来源单据号码
            faCard.setSourceBusinessName("期初导入");//来源单据名称
            faCategory.setId(faCardImportItem.getFaCategory().getInnerBusinessKey());//资产类别id
            product.setId(faCardImportItem.getProduct().getId());//商品ID
            product.setName(faCardImportItem.getProduct().getName());//商品名称
            faCard.setMeasurementUnit(faCardImportItem.getProduct().getUom().getName());//计量单位名称
            faCard.setOriginalValue(faCardImportItem.getOriginalValue() - faCardImportItem.getDepreciation());//原值
            faCard.setUseYear(faCardImportItem.getUseYear());//使用年限
            company.setId(faCardImport.getCompany().getId());//公司id
            String typeId = faCardImportItem.getFaCategory().getAssetType().getId();
            faCard.setFaType(typeId.equals("fixedAssets") ? "固定资产" : (typeId.equals("low") ? "低值易耗" : (typeId.equals("materials") ? "材料物质" : (typeId.equals("gift") ? "礼品" : "固定资产"))));//固定资产类型
            faCard.setQuantity(1);//数量
            faCard.setDepreciation(0.0);//折旧
            faCard.setResponsiblePerson(this.getPerson(request));//记账人
            faCard.setPurchaseDate(new Date());//购置日期
            faCard.setEnableDate(new Date());//启用日期
            faCard.setUseMonth(faCardImportItem.getUseMonth());//使用月限
            faCard.setEstimatedResidualValueRate(faCardImportItem.getFaCategory().getNetResidualValueRate());//预计残值率
            faCard.setDepreciationMethod(faCardImportItem.getFaCategory().getDepreciationMethod());//折旧方法
            faCard.setAnnualDepreciationRate(faCardImportItem.getAnnualDepreciationRate());//年折旧率
            faCard.setMonthlyDepreciationRate(faCardImportItem.getMonthlyDepreciationRate());//月折旧率
            faCard.setFaStatus("1");//资产状态
            dept.setId(faCardImportItem.getDept().getId());//部门id
            dept.setName(faCardImportItem.getDept().getName());//部门名称
            faCard.setFaSource("购入");//资产来源
            faCard.setFaWhereabouts(null);//资产去向
            faCard.setTransferInUnit(null);//转入单位
            faCard.setTransferUnit(null);//转出单位
            faCard.setNote("期初导入(单号:" + faCardImport.getId() + ")");
            faCard.setEvaluationMark("0");//评估标志
            faCard.setEvaluationOriginalValue(0.0);//评估原值
            faCard.setDepreciationMark(true);//折旧标记
            faCard.setRemainingDepreciationMonth(faCardImportItem.getRemainingDepreciationMonth());//剩余折旧月
            faCard.setCreator(((User)request.getCurrentUser()).getName());// 制单人
            faCard.setCreateDate(new Date());
            faCard.setApproveUid(this.getPerson(request));//审核人
            faCard.setApproveDate(new Date());//审核时间
            faCard.setBusinessState("0");//单据状态
            faCard.setResponsiblePerson(faCardImportItem.getResponsiblePerson());//负责人
            faCard.setCustodian(this.getPerson(request));//保管人
            faCard.setUsePlace(null);//使用地点
            faCard.setProduct(product);
            faCard.setDept(dept);
            faCard.setUseDept(dept);
            faCard.setFaCategory(faCategory);
            faCard.setCompany(company);
            faCard.setCustodian(faCardImportItem.getCustodian());//保管人
            if (faCardImportItem.isAccountingMark()){
                faCardService.beforeSave(faCard);
            }else{
                faCardService.beforeSaveNoAccount(faCard);
            }

        }

        return faCardImportRepository.saveAndFlush(faCardImport);

    }
    public Map importData(SimpleRequest request) throws Exception {

        JSONObject jsonData =  request.getJO();
        JSONObject importData = jsonData.getJSONObject("importData");
        JSONObject model = jsonData.getJSONObject("model");
        String companyId = model.getJSONObject("company").getString("id");

        Map requestMap = new LinkedHashMap();
        List<Map> items = new ArrayList<>();
        StringBuffer msg = new StringBuffer();
        importData.forEach((k, v) -> {

            JSONArray excl = (JSONArray) v;
            JSONArray header = (JSONArray) excl.get(0); //表格头部

            for (int i = 0; i < excl.size(); i++) {  //遍历每一行
                if (i == 0) continue; //跳过首行

                JSONArray lineData = (JSONArray) excl.get(i); //当前行
                if (lineData.size() == 0) continue;
               // 卡片编码  资产分类编码  资产类型  商品  折旧部门  购置日期 原值  折旧
                // 启用日期  使用年限  使用月限  年折旧率  月折旧率  剩余折旧月 资产状态  负责人 保管人 使用人,记账标记

                Map m = MapUtil.mapper(
                        "id", header.indexOf("卡片编码") < lineData.size() ? lineData.getString(header.indexOf("卡片编码")) : null,
                        "faId", header.indexOf("卡片编码") < lineData.size() ? lineData.getString(header.indexOf("卡片编码")) : null,
                        "faCategory", header.indexOf("资产分类编码") < lineData.size() ? lineData.getString(header.indexOf("资产分类编码")) : null,
                        "faType", header.indexOf("资产类型") < lineData.size() ? lineData.getString(header.indexOf("资产类型")) : null,
                        "faStatus", header.indexOf("资产状态") < lineData.size() ? lineData.getString(header.indexOf("资产状态")) : null,
                        "product", header.indexOf("商品") < lineData.size() ? lineData.getString(header.indexOf("商品")) : null,
                        "measurementUnit",header.indexOf("计量单位") < lineData.size() ? lineData.getString(header.indexOf("计量单位")) : null,
                        "dept", header.indexOf("部门") < lineData.size() ? lineData.getString(header.indexOf("部门")) : null,
                        "purchaseDate", header.indexOf("购置日期") < lineData.size() ? DateUtil.timeStampToStr(lineData.getLong(header.indexOf("购置日期"))) : null,
                        "originalValue", header.indexOf("原值") < lineData.size() ? lineData.getDouble(header.indexOf("原值")) : null,
                        "depreciation", header.indexOf("折旧") < lineData.size() ? lineData.getDouble(header.indexOf("折旧")) : null,
                        "enableDate", header.indexOf("启用日期") < lineData.size() ? DateUtil.timeStampToStr(lineData.getLong(header.indexOf("购置日期"))) : null,
                        "useYear", header.indexOf("使用年限") < lineData.size() ? lineData.getInteger(header.indexOf("使用年限")) : null,
                        "useMonth", header.indexOf("使用月限") < lineData.size() ? lineData.getInteger(header.indexOf("使用月限")) : null,
                        "annualDepreciationRate", header.indexOf("年折旧率") < lineData.size() ? lineData.getDouble(header.indexOf("年折旧率")) : null,
                        "monthlyDepreciationRate", header.indexOf("月折旧率") < lineData.size() ? lineData.getDouble(header.indexOf("月折旧率")) : null,
                        "remainingDepreciationMonth", header.indexOf("剩余折旧月") < lineData.size() ? lineData.getInteger(header.indexOf("剩余折旧月")) : null,
                        "responsiblePerson", header.indexOf("负责人") < lineData.size() ? lineData.getString(header.indexOf("负责人")) : null,
                        "custodian", header.indexOf("保管人") < lineData.size() ? lineData.getString(header.indexOf("保管人")) : null,
                        "user", header.indexOf("使用人") < lineData.size() ? lineData.getString(header.indexOf("使用人")) : null,
                        "accountingMark", header.indexOf("记账标记") < lineData.size() ? lineData.getBoolean(header.indexOf("记账标记")) : null

                );
                String message = convertData(m, companyId, i);
                msg.append(message);
                items.add(m);

            }
        });
        requestMap.put("msg",msg.toString());
        requestMap.put("items",items);
        return requestMap;
    }

    private String convertData(Map map,String companyId,int index) {
        String message = "";
        /*转换资产分类*/
        FaCategory faCategory = SpringManager.getBean(FaCategoryRepository.class).findOne(map.get("faCategory").toString());
        map.put("faCategory",faCategory);
        map.put("depreciationMethod",faCategory.getDepreciationMethod());
        /*转换商品*/
        Product product =SpringManager.getBean(ProductRepository.class).findOne(map.get("product").toString());
        if (product !=null){
           map.put("product",product);
        }else{
            message = message + "第"+index+"行"+ "商品不存在"+map.get("product").toString();
        }

        /*转换部门*/
        System.out.println("--------------"+index);
        Dept dept = SpringManager.getBean(DeptRepository.class).findOne(map.get("dept").toString());
        if (dept !=null){
            map.put("dept",dept);
            map.put("useDept",dept);
        }else{
            message = message + "第"+index+"行"+ "部门不存在"+map.get("dept").toString();
        }

        /*转换人员*/

        if (map.get("responsiblePerson") !=null){
            PartyRole partyRole = SpringManager.getBean(PartyRoleRepository.class).findEmployeeByName(map.get("responsiblePerson").toString()).get(0);
            map.put("responsiblePerson",partyRole);
            map.put("custodian",partyRole);
            map.put("user",partyRole);
        }else{
            map.put("responsiblePerson",null);
            map.put("custodian",null);
            map.put("user",null);
        }


        map.put("faStatus",1);

        return message;
    }

}
